package com.fulu.game.bi.service.impl.auth;

import cn.hutool.core.collection.CollectionUtil;
import com.fulu.game.bi.common.Constants;
import com.fulu.game.bi.entity.enums.StatusEnum;
import com.fulu.game.bi.entity.enums.PermissionTypeEnum;
import com.fulu.game.bi.entity.po.auth.BiPermission;
import com.fulu.game.bi.entity.po.auth.BiUser;
import com.fulu.game.bi.entity.vo.auth.permission.PermissionQueryVO;
import com.fulu.game.bi.entity.vo.auth.permission.PermissionSaveVO;
import com.fulu.game.bi.entity.vo.auth.permission.RoleVO;
import com.fulu.game.bi.enums.CommonlyOrderEnums;
import com.fulu.game.bi.mysql.bi.auth.BiPermissionDao;
import com.fulu.game.bi.redis.service.auth.BiPermissionService;
import com.fulu.game.bi.redis.service.auth.BiUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class PermissionServiceImpl implements BiPermissionService {

    @Autowired
    private BiPermissionDao biPermissionDao;

    @Autowired
    private BiUserService biUserService;


    /**
     * 构建树状结构
     */
    public List<BiPermission> buildTree(List<BiPermission> pidList){
        Map<Integer,List<BiPermission>> pidListMap =
                pidList.stream().collect(Collectors.groupingBy(BiPermission::getPid));
        pidList.stream().forEach(item->item.setChild(pidListMap.get(item.getId())));
        //返回结果也改为返回顶层节点的list
        return pidListMap.get(0);
    }

    @Override
    public RoleVO findAllByRoleId(Integer roleId) {
        PermissionQueryVO vo = new PermissionQueryVO();
        List<BiPermission> allPermissionList = biPermissionDao.listAll(vo);

        Set querySet = new HashSet();
        querySet.add(roleId);
        Set<BiPermission> roleRouterList = biPermissionDao.findByRoleList(querySet);

        Map<Integer, List<BiPermission>> idMapper = roleRouterList.stream().collect(Collectors.groupingBy(BiPermission::getId));

        // 设置router选中状态
        allPermissionList.forEach(v -> {
            v.setSelected(idMapper.containsKey(v.getId()));
        });

        List<BiPermission> tree = buildTree(allPermissionList);

        RoleVO sysRoleVO = new RoleVO();
        sysRoleVO.setRouterList(tree);

        return sysRoleVO;
    }

    @Override
    public PageInfo<BiPermission> list(PermissionQueryVO vo) {
        PageHelper.startPage(vo.getPageNum(), vo.getPageSize(), CommonlyOrderEnums.UPDATE_DESC.getValue());

        List<BiPermission> list = biPermissionDao.list(vo);

        return new PageInfo(list);
    }

    @Override
    public BiPermission save(PermissionSaveVO vo) {
        if (Objects.isNull(vo.getId())) {
            return createNewPermission(vo);
        }

        return updateExistPermission(vo);
    }

    private BiPermission updateExistPermission(PermissionSaveVO vo) {
        BiPermission permission = new BiPermission();
        BeanUtils.copyProperties(vo, permission);

        biPermissionDao.updateSelective(permission);

        return permission;
    }

    private BiPermission createNewPermission(PermissionSaveVO vo) {
        BiPermission permission = new BiPermission();
        BeanUtils.copyProperties(vo, permission);

        BiUser currentUser = biUserService.getCurrentUser();
        Date now = new Date();
        permission.setIsDel(StatusEnum.NO.getStatus());
        permission.setUpdateTime(now);
        permission.setCreateTime(now);
        permission.setType(PermissionTypeEnum.MENU.getType());
        permission.setOperatorId(currentUser.getId());
        permission.setOperatorName(currentUser.getName());
        permission.setComponent(Constants.DEFAULT_WORD);

        int res = biPermissionDao.insert(permission);

        log.info("新增权限：{} {}", res, permission);

        return permission;
    }


    @Override
    public BiPermission findById(Integer id) {
        return biPermissionDao.findById(id);
    }

    @Override
    public void deleteById(Integer id) {
        biPermissionDao.deleteById(id);
    }

    @Override
    public List<BiPermission> listAll() {
        return biPermissionDao.listAll(new PermissionQueryVO());
    }

    @Override
    public List<BiPermission> listAll(Integer userId) {
        if (Objects.isNull(userId)) {
            return listAll();
        }
        PermissionQueryVO vo = new PermissionQueryVO();
        vo.setUserId(userId);
        return biPermissionDao.list(vo);
    }
}
